package com.kuizii.discovery.config;

import com.kuizii.common.LiteServiceInstance;
import com.kuizii.common.LiteServiceRegistration;
import com.kuizii.discovery.client.*;
import com.kuizii.discovery.net.IOManager;
import com.kuizii.discovery.net.NettyIOManager;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@EnableConfigurationProperties(DiscoveryProperties.class)
@Configuration(proxyBeanMethods = false)
@ConditionalOnDiscoveryEnabled
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class})
public class LiteRegisterAutoConfiguration {


    @Bean
    @ConditionalOnMissingBean
    public LiteServiceInstance liteServiceInstance(DiscoveryProperties properties) {

        return new LiteServiceInstance(properties.getBindIp(), properties.getPort());
    }


    @Bean
    @ConditionalOnMissingBean
    public   IOManager ioManager(DiscoveryProperties properties) {
        NettyIOManager nettyIOManager = new NettyIOManager();
        nettyIOManager.init(properties);
        return nettyIOManager;
    }

    @Bean
    @ConditionalOnMissingBean
    public   LiteServiceRegistry liteServiceRegistry(IOManager ioManager, DiscoveryProperties properties) {
        return new LiteServiceRegistry(ioManager, properties);
    }

    @Bean
    @ConditionalOnMissingBean(value = Registration.class)
    public Registration liteServiceRegistration(DiscoveryProperties properties) {
        LiteServiceRegistration liteServiceRegistration = new LiteServiceRegistration(properties.getBindIp(), properties.getPort());
        liteServiceRegistration.setServiceId(properties.getServiceName());
        return liteServiceRegistration;
    }

    @Bean
    @ConditionalOnMissingBean
    public DiscoveryServer discoveryServer(IOManager ioManager, DiscoveryProperties properties) {
        return new DefaultDiscoveryServer(properties,ioManager);
    }
}
